/**
 * 将旧系统的设备数据同步到新系统
 */

import * as path from "path";
import * as fs from "fs";
import * as os from "os";

import dayjs from "dayjs";

import { deviceSave, getDeviceInfoByCode } from "./api/newApi";
import { getDeviceInfoList } from "./api/oldApi";

const __dirname = path.resolve();
const DIR_PATH = path.resolve(__dirname, "./downloadDevices");
const DEVICE_INF = path.resolve(DIR_PATH, "./device.json");
const SYNC_DEVICE_FILE_PATH = path.resolve(DIR_PATH, "./syncDevice.log");

let curDevice: null | any = null;

(async () => {
	try {
		main();
	} catch (err) {
		console.log("err: ", err instanceof Error ? err.message : err);
	}
})();

async function main() {
	try {
		if (!fs.existsSync(DIR_PATH)) fs.mkdirSync(DIR_PATH);

		const allDevice = await getDeviceInfoList().then((res) => res.data.data);
		if (allDevice.length === 0) {
			console.log("设备全部迁移完毕");
			process.exit(1);
		}

		for (let i = 0; i < allDevice.length; i++) {
			curDevice = allDevice[i];
			// 先查询有没有重复的
			const queryDevice = await getDeviceInfoByCode(curDevice.no).then((res) => res.data?.data || null);
			if (queryDevice) {
				const msg1 = `【${curDevice.no}】设备已存在`;
				console.log(msg1);
			} else {
				if (!curDevice.officeName) {
					const msg4 = `【${curDevice.no}】机构为空不迁移`;
					console.log(msg4);
					fs.appendFileSync(SYNC_DEVICE_FILE_PATH, `${msg4}${os.EOL.repeat(2)}`);
					continue;
				}
				console.log(`迁移【${curDevice.no}】`);
				const time = dayjs().format("YYYY-MM-DD HH:mm:ss");
				const sep = "寸";
				const [num, face] = curDevice.type.split(sep);
				const model = `${num}${sep}_${face}面`;
				const saveData = {
					officeCode: curDevice.officeId,
					officeName: curDevice.officeName,
					remarks: time + " 迁移上传",
					intoNetworkTime: time,
					status: "0",
					code: curDevice.no,
					name: `${curDevice.officeName}_${curDevice.area}_${curDevice.factory}_${model}`,
					isOnline: "0",
					factory: curDevice.factory,
					area: curDevice.area,
					model,
					systemVersion: "Android 7.1.2", // TODO
					softwareVersion: curDevice.version,
					playMode: "1",
					androidId: curDevice.id,
					mac: curDevice.mac,
					uuid: curDevice.id,
					resolutionRatio: curDevice.resolution,
					ip: "0.0.0.0" // TODO
				};
				const retData = await deviceSave(saveData).then((res) => res.data.data);
				const msg2 = `【${curDevice.no}】设备新增成功`;
				console.log(msg2);
				fs.appendFileSync(SYNC_DEVICE_FILE_PATH, `${msg2}${os.EOL}`);
				if (retData.code !== curDevice.no) {
					const msg3 = `新增的编号为【${retData.code}】不一致, 重新更新设备编号为【${curDevice.no}】`;
					console.log(msg3);
					fs.appendFileSync(SYNC_DEVICE_FILE_PATH, `${msg3}${os.EOL.repeat(2)}`);
					await deviceSave({
						...retData,
						code: curDevice.no,
						uuid: retData.id,
						androidId: retData.id
					});
				}
			}
		}
		console.log("success");
	} catch (err) {
		console.log("排期迁移失败: ", err instanceof Error ? err.message : err);
		// 记录失败的设备信息
		fs.promises.writeFile(DEVICE_INF, JSON.stringify(curDevice, null, 2));
	}
}
